<template>
  <!-- 配件信息 新增 -->
  <div>
    <!-- 表单 -->
    <FormPanel ref="form" labelWidth="100" :cols="3" :list="formList" :isSubmitBtn="false" @formChange="formChange"></FormPanel>
    <!-- 表格 -->
    <!-- <FilterTable
      ref="table"
      height="auto"
      :columns="columns"
      columnsRef="partPartOutboundRepairMaterialsComponentsPartInfo"
      :dataSource="dataSource"
      :onColumnsChange="columns => (this.columns = columns)"
    ></FilterTable> -->
  </div>
</template>

<script>
import { state, mutations } from './../store';
import { isAuthorized } from '@/utils/index';
import { getPartitionList } from '@/api/repair/repair/activitesManage';
import { getStorageList } from '@/api/part/partOutbound/repairMaterials/dict';
import { queryPartStock, searchTtRoLabour } from '@/api/part/partOutbound/repairMaterials/index.js';
import { dictionary } from '@/utils/dictMixin';
import { getWxlxSelect, getSfqfSelect } from '@/api/repair/repairReception/customer';

const jglx_dict = [
  { text: '终端建议零售VIP价格', value: 82481001, filedName: 'INSTRUCT_PRICE' },
  { text: '常规订货价', value: 82481002, filedName: 'PLAN_PRICE' },
  { text: '含税成本价', value: 82481003, filedName: 'COST_PRICE' },
  { text: '终端建议零售价格', value: 82481004, filedName: 'INSURANCE_PRICE' },
  { text: '索赔价', value: 82481005, filedName: 'CLAIM_PRICE' },
  { text: '最新进货价', value: 82481006, filedName: 'LATEST_PRICE' }
];

export default {
  name: 'cgrk_part_info',
  mixins: [dictionary],
  props: {
    partInfoRow: Object,
    type: String
  },
  data() {
    this.state = state;
    this.chargePartitionList = [];
    return {
      formList: this.createList(),
      columns: this.createColumns(),
      dataSource: []
    };
  },
  computed: {
    roNo() {
      return state.roNo;
    }
  },
  watch: {
    partInfoRow(partInfoRow) {
      console.log('watch partInfo', partInfoRow);
      this.queryPartStock(partInfoRow);
    }
  },
  mounted() {
    window.cgrk_part_info = this;
    console.log('cgrk_part_info mounted');
    this.getSfqfSelect();
    this.getSystemAuthority();
    this.getBrands();
    this.getPartitionList();
  },
  methods: {
    async getSfqfSelect() {
      let res = await getSfqfSelect();
      if (res.resultCode == 200) {
        this.formList.find(x => x.fieldName === 'CHARGE_PARTITION_CODE').itemList = res.data.map(x => {
          return { text: x.CHARGE_PARTITION_NAME, value: x.CHARGE_PARTITION_CODE };
        });
      }
    },
    // 查询配件信息  通过双击配件搜索列表传来的参数
    async queryPartStock(row) {
      console.log('传过来的111', row);
      const res = await queryPartStock({
        partNo: row['PART_NO'],
        storageCode: row['STORAGE_CODE']
      });
      if (res.resultCode != 200) {
        console.log('查询配件 失败', res);
        return;
      }
      const part = res.data.rows[0];
      console.log('查询配件 成功222', part);
      // 整合配件信息
      // const partInfo = Object.assign({}, row, part);
      const partInfo = Object.assign({}, row, part);
      console.log('整合后的配件信息', partInfo);
      this.initDataSource(partInfo);
      // this.formList.forEach(element => {
      //   element.initialValue = partInfo[element.fieldName];
      // });

      // this.dataSource = [partInfo];
    },
    async initDataSource(partInfo) {
      const partInfoRow = this.partInfoRow;
      this.partInfoRow.PART_SALES_PRICE_COPY = partInfoRow['SALES_PRICE'] || 0;
      // 仓库 .find(x => x.fieldName === '')
      // this.formList.find(x => x.fieldName === 'STORAGE_CODE').initialValue = partInfoRow['STORAGE_CODE'];
      // // 配件代码
      // this.formList.find(x => x.fieldName === 'PART_NO').initialValue = partInfoRow['PART_NO'];
      // // 配件名称
      // this.formList.find(x => x.fieldName === 'PART_NAME').initialValue = partInfoRow['PART_NAME'];
      // 价格系数
      this.formList.find(x => x.fieldName === 'PRICE_RATE').initialValue = 1;
      // 价格类型
      this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481002;
      // 配件销售单价
      this.formList.find(x => x.fieldName === 'PART_SALES_PRICE').initialValue = partInfoRow['SALES_PRICE'] || 0;
      // 配件数量
      this.formList.find(x => x.fieldName === 'PART_QUANTITY').initialValue = partInfoRow['PART_QUANTITY'] || 1;
      // 配件销售金额
      this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = partInfoRow['SALES_PRICE'] || 0;
      // 收费区分
      // this.formList[10].initialValue = '';
      this.dataSource = [partInfo];
    },
    createList() {
      return [
        // {
        //   type: 'SELECT',
        //   label: '仓库名称',
        //   fieldName: 'STORAGE_CODE',
        //   initialValue: '',
        //   placeholder: '',
        //   // itemList: state.dict_ck,
        //   itemList: [],
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '配件代码',
        //   fieldName: 'PART_NO',
        //   initialValue: '',
        //   placeholder: '',
        //   disabled: true
        // },
        // {
        //   type: 'INPUT',
        //   label: '配件名称',
        //   fieldName: 'PART_NAME',
        //   initialValue: '',
        //   placeholder: '',
        //   disabled: true
        // },
        {
          type: 'SELECT',
          label: '主要配件',
          fieldName: 'IS_MAIN_PART',
          initialValue: 10041002,
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '价格类型',
          fieldName: 'PRICE_TYPE',
          placeholder: '',
          hidden: true,
          itemList: this.createDictList('8248'),
          rules: [{ type: 'number', required: true, message: '请选择价格类型', trigger: ['blur', 'change'] }],
          change: val => {
            this.price_type_change(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '价格系数',
          fieldName: 'PRICE_RATE',
          hidden: true,
          rules: [{ required: true, message: '请输入价格系数', trigger: 'blur' }],
          precision: 2,
          initialValue: '1',
          placeholder: '',
          min: 1,
          change: val => {
            this.price_rate_change(val);
          }
        },
        {
          type: 'INPUT_NUMBER',
          label: '发料单价',
          fieldName: 'PART_SALES_PRICE',
          precision: 2,
          initialValue: 0,
          placeholder: '',
          hidden: true,
          rules: [{ required: true, message: '请输入配件销售单价', trigger: ['blur', 'change'] }],
          change: val => {
            // this.part_sales_price_change(val);
          }
        },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '发料数量',
        //   fieldName: 'PART_QUANTITY',
        //   precision: 2,
        //   initialValue: 1,
        //   placeholder: '',
        //   rules: [{ type: 'number', required: true, message: '请输入配件数量', trigger: ['blur', 'change'] }],
        //   change: val => {
        //     this.part_quantity_change(val);
        //   }
        // },
        {
          type: 'INPUT',
          label: '发料金额',
          fieldName: 'PART_SALES_AMOUNT',
          precision: 2,
          initialValue: '',
          placeholder: '',
          hidden: true
        },
        {
          type: 'SELECT',
          label: '收费区分',
          fieldName: 'CHARGE_PARTITION_CODE',
          hidden: true,
          initialValue: '',
          itemList: [],
          rules: [{ required: true, message: '请选择收费区分', trigger: ['blur'] }],
          change: val => {
            this.charge_partition_code_change(val);
          }
        },
        {
          type: 'SELECT',
          label: '维修项目',
          fieldName: 'LABOUR_CODE',
          initialValue: '',
          placeholder: '',
          itemList: state.dict_xlxm,
          change: val => {
            this.searchTtRoLabour(val);
          },
          rules: [{ type: 'string', required: true, message: '这是必填字段', trigger: ['blur', 'change'] }]
        }
        // {
        //   type: 'INPUT',
        //   label: '备注',
        //   fieldName: 'REMARK'
        // }
      ];
    },
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },

        {
          title: '终端建议零售VIP价格',
          sorter: true,
          dataIndex: 'INSTRUCT_PRICE',
          precision: 2
        },
        {
          title: '常规订货价',
          sorter: true,
          dataIndex: 'PLAN_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '含税成本价',
          sorter: true,
          dataIndex: 'COST_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },

        {
          title: '索赔价',
          sorter: true,
          dataIndex: 'CLAIM_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '终端建议零售价格',
          sorter: true,
          dataIndex: 'INSURANCE_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '最新进货价',
          sorter: true,
          dataIndex: 'LATEST_PRICE',
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '账面库存',
          sorter: true,
          precision: 2,
          dataIndex: 'STOCK_QUANTITY'
        },
        {
          title: '可用库存',
          sorter: true,
          precision: 2,
          dataIndex: 'USEABLE_STOCK'
        },
        {
          title: '锁定量',
          sorter: true,
          dataIndex: 'LOCKED_QUANTITY',
          precision: 2
        },
        {
          title: '配件类别',
          sorter: true,
          dataIndex: 'PART_GROUP_CODE',
          editable: false,
          editType: 'select',
          editItems: this.createDictList(8247)
        },
        {
          title: '单位',
          sorter: true,
          dataIndex: 'UNIT_NAME'
        }
      ];
    },

    async getBrands() {
      const res = await getStorageList();
      this.formList.find(x => x.fieldName == 'STORAGE_CODE').itemList = res.data.map(x => ({ value: x.STORAGE_CODE, text: x.STORAGE_NAME }));
    },

    // 收费区分下拉框
    async getPartitionList() {
      const res = await getPartitionList();
      this.chargePartitionList = res.data.map(x => ({ value: x.CHARGE_PARTITION_CODE, text: x.CHARGE_PARTITION_NAME }));
      this.formList.find(x => x.fieldName == 'CHARGE_PARTITION_CODE').itemList = this.chargePartitionList;
    },

    // 选择项目维修时改变的收费区分
    async searchTtRoLabour(val) {
      let LABOUR_CODE = val.split('~')[0];
      console.log(val, 'val');
      console.log(LABOUR_CODE, 'LABOUR_CODE');
      const res = await searchTtRoLabour({ roNo: this.roNo });
      res.data.rows.forEach((item, idx) => {
        if (item.LABOUR_CODE == LABOUR_CODE) {
          this.formList.find(x => x.fieldName == 'CHARGE_PARTITION_CODE').initialValue = res.data.rows[idx].CHARGE_PARTITION_CODE;
          this.charge_partition_code_change(res.data.rows[idx].CHARGE_PARTITION_CODE);
        }
      });
    },
    // 收集表达数据 Add页面触发
    formChange(val) {
      console.log('formChange', val);
      let row = Object.assign({}, this.partInfoRow, this.dataSource[0], val, { $index_edit: this.partInfoRow.$index_edit });
      // 判断 配件是否已选
      if (!val['PART_NO']) {
        this.$notify({
          title: '警告',
          message: '未选择配件',
          type: 'warning'
        });
        console.log('未选择配件');
        return;
      }
      this.formList.find(x => {
        if (x.hidden == true) {
          console.log(x.fieldName, 'filedName');
          row[x.fieldName] = x.initialValue;
        }
      });
      let temp = this.chargePartitionList.find(x => x.value == row.CHARGE_PARTITION_CODE);
      if (temp) {
        row.CHARGE_PARTITION_NAME = temp.text || '';
      }
      this.$emit('getEditPartInfo', row);
    },
    /** 价格计算逻辑 S */
    // 价格类型 变化  计算 配件销售单价 配件销售金额
    price_type_change(price_type) {
      var val = price_type;
      console.log('价格类型 change', price_type);
      // 计算 配件销售单价(价格类型*价格系数)  配件销售金额(配件销售单价*配件数量)
      this.calculateLogic(price_type);
    },
    // 价格系数变化 计算 配件销售单价(价格类型*价格系数)  配件销售金额(配件销售单价*配件数量)
    price_rate_change(price_rate) {
      var priceRate = price_rate;
      // 计算 配件销售单价(价格类型*价格系数)  配件销售金额(配件销售单价*配件数量)
      const priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
      this.calculateLogic(priceType, priceRate);
    },
    // 配件销售单价变化 计算价格系数(销售单价 / 价格类型) 和 销售金额
    // part_sales_price_change(part_sales_price) {
    //   var val = part_sales_price;
    //   console.log('配件销售单价 PART_SALES_PRICE change', val);
    //   // 计算价格系数(销售单价 / 价格类型) 和 销售金额
    //   const PART_SALES_PRICE = val;
    //   // const PRICE_RATE = Number(val) / 100;
    //   const priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
    //   const filedName = jglx_dict.find(x => x.value == priceType).filedName;
    //   const PRICE_TYPE = this.dataSource[0][filedName] || 1; // 默认是1
    //   const PRICE_RATE = Number(val) / PRICE_TYPE;
    //   this.formList.find(x => x.fieldName === 'PRICE_RATE').initialValue = PRICE_RATE;
    //   const PART_QUANTITY = this.formList.find(x => x.fieldName === 'PART_QUANTITY').initialValue;
    //   const PART_SALES_AMOUNT = Number(PART_SALES_PRICE) * Number(PART_QUANTITY);
    //   this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = PART_SALES_AMOUNT.toFixed(2);
    // },
    part_quantity_change(part_quantity) {
      var val = part_quantity;
      console.log('配件数量 PART_QUANTITY change', val);
      // 计算配件销售金额 (配件销售单价*配件数量)
      // const PART_SALES_PRICE = this.formList.find(x => x.fieldName === 'PART_SALES_PRICE').initialValue;
      const priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
      this.$nextTick(x => {
        this.calculateLogic(priceType);
      });
      // const PART_SALES_PRICE = this.partInfoRow['SALES_PRICE'] || 0;
      // console.log(part);
      // const PART_SALES_AMOUNT = Number(PART_SALES_PRICE) * Number(val);
      // this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = PART_SALES_AMOUNT.toFixed(2);
    },
    // 收费区分变化
    charge_partition_code_change(charge_partition_code) {
      console.log('收费区分 change', charge_partition_code);
      // a)选择免费时，价格类型自动选择索赔 82481005
      // b)选择自费时，价格类型自动选择终端建议零售VIP价格 82481001
      // c)选择保险时，价格类型自动选择终端建议零售价格 82481004
      // d)选择经销商时，价格类型自动选择成本价 82481003
      // 索赔 - 索赔 82481005

      // 82481001-终端建议零售VIP价格
      // 82481002-常规订货价
      // 82481003-含税成本价
      // 82481004-终端建议零售价格
      // 82481005-索赔价
      // 82481006-最新进货价
      let priceType = 82481001;
      let chargeName = this.chargePartitionList.find(x => x.value == charge_partition_code).text;
      if (chargeName == '免费') {
        // 免费 - 价格类型索赔
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481005;
      }
      if (chargeName == '自费') {
        // 自费
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481001;
      }
      if (chargeName == '保险') {
        // 保险
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481004;
      }
      if (chargeName == '经销商') {
        // 经销商
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481003;
      }
      if (chargeName == '索赔') {
        // 索赔
        priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = 82481005;
      }
      // let priceType = this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue;
      this.calculateLogic(priceType);
    },

    calculateLogic(price_type, price_rate, part_sales_price, charge_partition_code) {
      // 设置PRICE_TYPE
      this.formList.find(x => x.fieldName === 'PRICE_TYPE').initialValue = price_type;
      const filedName = jglx_dict.find(x => x.value == price_type).filedName;
      const PRICE_TYPE = this.dataSource[0][filedName] || 0; // 默认是1
      const PRICE_RATE = price_rate ? price_rate : this.formList.find(x => x.fieldName === 'PRICE_RATE').initialValue; // 默认也是1
      const PART_SALES_PRICE = Number(PRICE_TYPE) * Number(PRICE_RATE);
      // 设置单价
      this.formList.find(x => x.fieldName === 'PART_SALES_PRICE').initialValue = PART_SALES_PRICE.toFixed(2);

      const PART_QUANTITY = this.formList.find(x => x.fieldName === 'PART_QUANTITY').initialValue;
      if (PART_QUANTITY) {
        const PART_SALES_AMOUNT = Number(PART_SALES_PRICE) * Number(PART_QUANTITY);
        // 设置总价
        this.formList.find(x => x.fieldName === 'PART_SALES_AMOUNT').initialValue = PART_SALES_AMOUNT.toFixed(2);
      }
    },
    /** 价格计算逻辑 E */

    // 获取系统权限
    getSystemAuthority() {
      //   // 保修信息
      //   console.log('11111------------');
      //   // 收费区分
      //   let chargePartitionFlag = isAuthorized('1313', '13131002');
      //   console.log(chargePartitionFlag, 'chargePartitionFlag');
      //   // 销售单价
      //   let salesPriceFlag = isAuthorized('1313', '13131001');
      //   // 价格类型
      //   let priceTypeFlag = isAuthorized('1313', '13131010');
      //   if (chargePartitionFlag) {
      //     console.log('13131002----------------------------------');
      //     this.formList.find(x => x.fieldName == 'CHARGE_PARTITION_CODE').disabled = false;
      //   }
      //   if (salesPriceFlag) {
      //     this.formList.find(x => x.fieldName == 'PART_SALES_PRICE').disabled = false;
      //   }
      //   if (priceTypeFlag) {
      //     this.formList.find(x => x.fieldName === 'PRICE_TYPE').disabled = false;
      //   }
    }
  }
};
</script>

<style></style>
